package com.rabbitmq.learn.pubsub;

import com.rabbitmq.client.*;
import com.rabbitmq.learn.common.ConnectionUtils;
import com.rabbitmq.learn.common.RabbitMqConstant;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by Lxk on 2019/8/11.
 */
@SuppressWarnings("Duplicates")
public class Receiver2 {

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection con = ConnectionUtils.getConnection();

        final Channel channel = con.createChannel();

        channel.basicQos(1);

        channel.queueDeclare(RabbitMqConstant.PubSub.QUEUE_NAME2,false,false,false,null);

        channel.queueBind(RabbitMqConstant.PubSub.QUEUE_NAME2,RabbitMqConstant.PubSub.EXCHANGE_NAME,"");

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body,"utf-8");
                System.out.println("receiver2 receive: " + msg);
                try{
                    Thread.sleep(2000);
                }catch (InterruptedException e){
                    e.printStackTrace();;
                }finally {
                    System.out.println("[2] done");
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };

        boolean autoAck = false;
        channel.basicConsume(RabbitMqConstant.PubSub.QUEUE_NAME2,autoAck,consumer);
    }

}
